import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import { logoutApi } from '@/settings'
NProgress.configure({ showSpinner: false })
// 白名单
const whiteList = ['/login', '/error/401', '/error/403', '/error/404', '/error/500', '/error/5XX']

// 路由校验
export const router_next_permission = options => {
  const { to, next, failUrl } = options
  console.log(store.getters.roles, 'rolse')
  if (store.getters && store.getters.roles && store.getters.roles.length) {
    const roles = store.getters.roles
    let hasPermission
    if (Array.isArray(to.meta.roles) && to.meta.roles.length > 0) {
      hasPermission = to.meta.roles.some(role => {
        return roles.includes(role)
      })
    } else {
      hasPermission = true
    }
    if (!hasPermission) {
      if (failUrl) {
        window.location.href = failUrl
      } else {
        next({ path: '/error/404' })
      }
    } else {
      next()
    }
  } else {
    store.dispatch('userinfo/getUser').then((res) => {
      if (res && res.data.roles) {
        const permission = to.meta.roles
        const roles = res.data.roles
        let hasPermission
        if (Array.isArray(permission) === false) {
          hasPermission = true
        } else {
          hasPermission = permission.some(role => {
            return roles.includes(role)
          })
        }
        // 无权限
        if (Array.isArray(permission) && permission.length && !hasPermission) {
          if (failUrl) {
            window.location.href = failUrl
          } else {
            next({ path: '/error/404' })
          }
        } else {
          // 有权限
          if (to.path === '/login') {
            next({ path: '/' })
          } else {
            next()
          }
        }
      } else {
        Message({
          showClose: true,
          message: '没有获取到账号类型',
          type: 'error'
        })
        global.location = logoutApi
      }
    }).catch(() => {
      Message({
        showClose: true,
        message: '没有获取到账号类型',
        type: 'error'
      })
      global.location = logoutApi
    })
  }
}

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // 先校验是否在白名单中
  if (whiteList.indexOf(to.path) !== -1) {
    next()
  } else {
    // 身份验证
    router_next_permission({
      to,
      from,
      next
      // failUrl: '' // failUrl的缺省值为 next({path: '/404'})
    })
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})

router.onError(error => {
  const cannotFindModule = 'Cannot find module'
  const { message } = error

  if (message && message.indexOf(cannotFindModule) > -1) {
    router.replace('/error/404')
    NProgress.done()
  }
})
